<template>
    <el-tree ref="treeRef" :data="arr" @check="check" show-checkbox :props="defaultProps" node-key="id"
        :check-on-click-node="false" :expand-on-click-node="false" check-on-click-node="false"
        :default-checked-keys="checkedKeys" class="treeRef" @node-click="nodeClick">
        <template #default="{ node, data }">
            <span class="tree-span">{{ node.label }}</span>
            <input type="color" v-model="data.color" @change="changeColor(data, node)" />
        </template>
    </el-tree>
    <!-- <button @click="random()">设置随机颜色</button>
    <button @click="reset()">恢复默认颜色</button> -->

</template>
<script setup>
import { ref, watch, computed, onMounted } from 'vue'

import { getRandomHexColor } from "@/scripts/utils"
import { getProjectManager } from "@/scripts/getProjectManager";

const objm = getProjectManager();

const virtualLayer = objm.cimrtsManager.virtualLayer

const props = defineProps({
    arr: {
        type: Array,
        default: () => []
    }
})
const emits = defineEmits(['checkTree',])

const defaultProps = {
    children: 'children',
    label: 'label',
    id: 'value',

}
const checkedKeys = computed(() => {
    const keys = [];
    const collectCheckedKeys = (items) => {
        items.forEach(item => {
            if (item.visible) {
                keys.push(item.id); // 根据条件添加 id
            }
            if (item.children && item.children.length > 0) {
                collectCheckedKeys(item.children);
            }
        });
    };
    collectCheckedKeys(props.arr);
    return keys;
});

const updateVisibility = (items, checkedKeys) => {
    items.forEach(item => {
        checkedKeys.includes(item.id) ? item.visible = true : item.visible = false;
        // 如果有子项，递归调用
        if (item.children && item.children.length > 0) {
            updateVisibility(item.children, checkedKeys);
        }
    });
}

/**
 * 组织成接口需要的格式
 * @param items 
 */
const buildLayerConfig = (items) => {

    const layerConfig = []; // 初始化一个新的对象来存储结果
    items.forEach(item => {
        const config = {
            dataset: item.dataset,
            layer: item.value,
            value: {
                visible: item.visible, // 使用 item.visible
                color: item.color
            },
        }
        layerConfig.push(config)
        // 如果有子项，递归调用并合并结果
        if (item.children && item.children.length > 0) {
            const childConfig = buildLayerConfig(item.children);
            layerConfig.push(...childConfig); // 合并子项的配置
        }
    });

    return layerConfig; // 返回构建的配置
};

// 生成随机颜色
const getRandomColor = (items) => {
    const layerConfig = []; // 初始化一个新的对象来存储结果
    items.forEach(item => {
        const config = {
            dataset: item.dataset,
            layer: item.value,
            value: {
                visible: item.visible, // 使用 item.visible
                color: getRandomHexColor()
            },
        }
        layerConfig.push(config)
        item.color = config.value.color
        // 如果有子项，递归调用并合并结果
        if (item.children && item.children.length > 0) {
            const childConfig = getRandomColor(item.children);
            layerConfig.push(...childConfig); // 合并子项的配置
        }
    });

    return layerConfig; // 返回构建的配置
}

// 恢复初始颜色
const resetColor = (items) => {
    const layerConfig = []; // 初始化一个新的对象来存储结果
    items.forEach(item => {
        const config = {
            dataset: item.dataset,
            layer: item.value,
            value: {
                visible: item.visible, // 使用 item.visible
                color: '#FFFFFF'
            },
        }
        layerConfig.push(config)
        item.color = config.value.color
        // 如果有子项，递归调用并合并结果
        if (item.children && item.children.length > 0) {
            const childConfig = resetColor(item.children);
            layerConfig.push(...childConfig); // 合并子项的配置
        }
    });

    return layerConfig; // 返回构建的配置
}



const treeClickCnt = ref(0)
let treeClickTimeout = null
const treeClickId = ref("")

// 点击节点
const nodeClick = async (data, a, b, event) => {

    event.stopPropagation()

    // 如果点击的id不相同，则重置点击次数
    if (data.id != treeClickId.value) {
        treeClickCnt.value = 0;
    }
    treeClickId.value = data.id;
    treeClickCnt.value++;

    // 注册清空点击次数计时器任务
    window.clearTimeout(treeClickTimeout);
    treeClickTimeout = window.setTimeout(() => {
        treeClickCnt.value = 0;
    }, 300);

    // 连续点击多次则不做任何事情
    if (treeClickCnt.value > 2) return;
    // 点击一次时单击事件
    if (treeClickCnt.value == 1) {
        // 单击事件
        // console.log('单击');
    }
    // 点击两次时双击事件
    if (treeClickCnt.value == 2) {
        if (data.value != "") {
            // 双击事件
            const { rectangle, radius } = await virtualLayer.queryBoxByLayer(data.id);
            objm.activeViewer.flyToBoundingSphere(rectangle, radius)
        } else {
            const datasets = objm.cimrtsManager.tileServiceInfo.datasets
            const dataset = datasets.find((item) => item.idx === data.dataset)
            const { lonLatBox,lonLat } = dataset
            const radius = lonLat.sphereRadius * 3 + lonLatBox.maxZ
            const rectangle = [lonLatBox.minX, lonLatBox.minY, lonLatBox.maxX, lonLatBox.maxY]
            objm.activeViewer.flyToBoundingSphere(rectangle, radius)
        }

    }

}

// 修改复选框
const check = (data, node) => {
    updateVisibility(props.arr, [...node.checkedKeys]);
    const finalConfig = buildLayerConfig(props.arr); // 执行构建并获取结果
    emits('checkTree', finalConfig);
};

// 修改颜色
const changeColor = (data, node) => {
    const finalConfig = buildLayerConfig(props.arr); // 执行构建并获取结果
    emits('checkTree', finalConfig);
}

// 随机颜色
const random = () => {
    const finalConfig = getRandomColor(props.arr); // 执行构建并获取结果
    emits('checkTree', finalConfig);
}

// 重置
const reset = () => {
    const finalConfig = resetColor(props.arr); // 执行构建并获取结果
    emits('checkTree', finalConfig);
}

// onMounted(() => {
//     const finalConfig = buildLayerConfig(props.arr);
//     emits('checkTree', finalConfig);
// })

//暴露组件内部法
defineExpose({
    random,
    reset
});

</script>
<style scoped>
input[type="color"] {
    position: absolute;
    right: 0;
    appearance: none;
    padding: 0;
    margin: 3px 8px;
    border: 1px solid gray;
    outline: none;
    background: transparent;
    cursor: pointer;
    width: 23px;
    height: 23px;
}

input[type="color"]::-webkit-color-swatch-wrapper {
    padding: 0;
    border: none;
}

input[type="color"]::-webkit-color-swatch {
    border: none;
}

.custom-tree-node {
    flex: 1;
    height: 30px;
    font-size: 14px;
    padding-right: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.custom-tree-node .el-input {
    height: 26px;
    width: 236px;
}


.right-align {
    margin-left: auto;
    padding-right: 10px;
}

.tree-span {
    display: inline-block;
    width: 73%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.treeRef {
    height: calc(100% - 40px);
    overflow: auto;
}
</style>
